package com.jf3q.common.utils;

import com.aliyun.tea.TeaException;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.google.gson.Gson;
import com.jf3q.common.exception.JfException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * 阿里云视频点播工具类
 */
@Component
public class VodUtils {
    @Value("${ali.vod.endpoint}")
    private String endpoint;
    @Value("${ali.accesskeyId}")
    private String accessKeyId;
    @Value("${ali.secretAccesskey}")
    private String accessKeySecret;

    /**
     * 上传视频文件到阿里云
     * @param file
     * @return
     */

    public String uploadVod(MultipartFile file){

        try {
            String fileName = file.getOriginalFilename();
            String title = fileName.substring(0, fileName.lastIndexOf("."));
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, file.getInputStream());

            /* 是否使用默认水印（可选），指定模板组ID时，根据模板组配置确定是否使用默认水印*/
            request.setShowWaterMark(true);
            /* 自定义消息回调设置及上传加速设置（可选）, Extend为自定义扩展设置，MessageCallback为消息回调设置，AccelerateConfig为上传加速设置（上传加速功能需要先申请开通后才能使用）*/
            //request.setUserData("{\"Extend\":{\"test\":\"www\",\"localId\":\"xxxx\"},\"MessageCallback\":{\"CallbackType\":\"http\",\"CallbackURL\":\"http://example.aliyundoc.com\"},\"AccelerateConfig\":{\"Type\":\"oss\",\"Domain\":\"****Bucket.oss-accelerate.aliyuncs.com\"}}");
            /* 视频分类ID（可选） */
            request.setCateId(1000483671L);
            /* 视频标签，多个用逗号分隔（可选） */
            //request.setTags("标签1,标签2");
            /* 视频描述（可选）*/
            //request.setDescription("视频描述");
            /* 封面图片（可选）*/
            //request.setCoverURL("http://cover.example.com/image_01.jpg");
            /* 模板组ID（可选）*/
            request.setTemplateGroupId("d87ac4d2b32c7ffad68bf15a1c8728ac");
            /* 工作流ID（可选）*/
            //request.setWorkflowId("d4430d07361f0*be1339577859b0****");
            /* 存储区域（可选）*/
            //request.setStorageLocation("in-201703232118266-5sejd****.oss-cn-shanghai.aliyuncs.com");
            /* 开启默认上传进度回调 */
            // request.setPrintProgress(true);
            /* 设置自定义上传进度回调（必须继承 VoDProgressListener） */
            /*默认关闭。如果开启了这个功能，上传过程中服务端会在日志中返回上传详情。如果不需要接收此消息，需关闭此功能*/
            // request.setProgressListener(new PutObjectProgressListener());
            /* 设置应用ID*/
            //request.setAppId("app-100****");
            /* 点播服务接入点 */
            //request.setApiRegionId("cn-shanghai");
            /* ECS部署区域*/
            // request.setEcsRegionId("cn-shanghai");

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
            if (response.isSuccess()) {
                System.out.print("VideoId=" + response.getVideoId() + "\n");
            }else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
                throw new RuntimeException(response.getMessage());
            }

            return response.getVideoId();//上传到阿里云的视频id
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("视频上传失败");

        }

    }

    public  com.aliyun.vod20170321.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/vod
        config.endpoint = endpoint;
        return new com.aliyun.vod20170321.Client(config);
    }
    /**
     * 获取播放凭证
     * @param videoId
     * @return
     * @throws Exception
     */
    public String getVideoPlayAuth(String videoId)  {
        try {

        com.aliyun.vod20170321.Client client =createClient();
        com.aliyun.vod20170321.models.GetVideoPlayAuthRequest getVideoPlayAuthRequest = new com.aliyun.vod20170321.models.GetVideoPlayAuthRequest()
                .setVideoId(videoId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            // 复制代码运行请自行打印 API 的返回值
            com.aliyun.vod20170321.models.GetVideoPlayAuthResponse resp = client.getVideoPlayAuthWithOptions(getVideoPlayAuthRequest, runtime);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
            return resp.getBody().getPlayAuth();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取播放凭证失败");

        }

    }

    /**
     *  删除阿里云视频
     */
    public void del(String vid)  {
        try {
            com.aliyun.vod20170321.Client client =createClient();

            com.aliyun.vod20170321.models.DeleteVideoRequest deleteVideoRequest = new com.aliyun.vod20170321.models.DeleteVideoRequest();
            deleteVideoRequest.setVideoIds(vid);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            // 复制代码运行请自行打印 API 的返回值
            client.deleteVideoWithOptions(deleteVideoRequest, runtime);

        } catch (Exception e) {
            throw new RuntimeException("删除视频失败");
        }

    }
}
